package ubiqweb.spring3.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import ubiqweb.spring3.model.Registration;
import ubiqweb.spring3.model.LoginDetails;
import ubiqweb.spring3.service.UserService;
import ubiqweb.spring3.model.ChangePassword;


@Controller
@RequestMapping("/changePassword.html")
public class ChangePasswordController {
	@Autowired
	private ChangePasswordValidation changePasswordValidation;
	
	@Autowired
	  private UserService userService;


	public void setChangePasswordValidation(
			ChangePasswordValidation changePasswordValidation) {
		this.changePasswordValidation = changePasswordValidation;
	}


	// Display the form on the get request
	@SuppressWarnings("unchecked")
	@RequestMapping(method = RequestMethod.GET)
	public String showChangePassword(Map model) {
		ChangePassword changePassword = new ChangePassword();
		model.put("changePassword", changePassword);		
		return "changePassword";
	}

	// Process the form.
	@RequestMapping(method = RequestMethod.POST)
	public String processRegistration(@Valid ChangePassword changePassword,
			BindingResult result, HttpSession session) {
		// set custom Validation by user
		String userId = session.getAttribute("sessionUsrID").toString();
		List<LoginDetails> loginDetails = userService.listLoginDetails(userId);
		
		changePasswordValidation.validate(changePassword, result, loginDetails.get(0).getPassword());
		if (result.hasErrors()) {
			return "changePassword";
		}
		
		loginDetails.get(0).setPassword(changePassword.getNewPassword());
		userService.saveLoginDetails(loginDetails.get(0));
		
		return "home";
	}
}
